<template>
  <BasicModal v-bind="$attrs" @register="register" showFooter :title="getTitle" width="70%" @ok="handleSubmit"
    @cancel="cancelFn" :loading="loading" :ok-button-props="{ loading }" :show-ok-btn="!dataJson.id">

    <div style="width: 100%; height: 100%">
      <!-- v-on="gridEvents" overflow: hidden -->
      <div style="margin-left: 15px;" v-if="waitList.length">
        等待处理:
        <div class="table-header-btn" v-for="item in waitList">
          <span style="padding-right: 5px;">{{ item.createTime }}</span>
          <span v-for="item in waitList" @click="openWaitFn(item)" :style="{ color: item.status ? 'green' : 'red' }">{{
            item.status ? "处理完成,请点击此处提交审批" : "处理中" }}</span>
          <Spin v-if="item.status == 0"></Spin>
        </div>

      </div>
      <div style="height: 450px;">
        <vxe-grid ref="tableRef" v-bind="gridOptions">
          <template #toolbar_buttons>

          </template>
          <template #footer_totalAllPrice>
            <span style="color: red;">{{ totalObj.totalAllPrice }}{{ totalObj.totalAllPrice ? '元' : '' }} </span>
          </template>
          <template #footer_orderCommissionPrice>
            <span style="color: red;">{{ totalObj.orderCommissionPrice }}{{ totalObj.orderCommissionPrice ? '元' : ''
            }}</span>
          </template>
          <template #footer_receiverUserPrice>
            <span style="color: red;">{{ totalObj.receiverUserPrice }}{{ totalObj.receiverUserPrice ? '元' : '' }}</span>
          </template>
          <template #footer_manageUserPrice>
            <span style="color: red;">{{ totalObj.manageUserPrice }}{{ totalObj.manageUserPrice ? '元' : '' }}</span>
          </template>
          <template #footer_merchandiserUserPrice>
            <span style="color: red;">{{ totalObj.merchandiserUserPrice }}{{ totalObj.merchandiserUserPrice ? '元' : ''
            }}</span>
          </template>

          <template #footer_xiangMuGroupPrice>
            <span style="color: red;">{{ totalObj.xiangMuGroupPrice }}{{ totalObj.xiangMuGroupPrice ? '元' : '' }}</span>
          </template>
          <template #footer_jiJingPrice>
            <span style="color: red;">{{ totalObj.jiJingPrice }}{{ totalObj.jiJingPrice ? '元' : '' }}</span>
          </template>
        </vxe-grid>
      </div>

      <Modal v-model:visible="applyViewShow" title="审批详情" @ok="subFn" :okButtonProps="{ loading }" @cancel="subClose">
        <div>
          <div style="margin-bottom: 5px;">审批详情:</div>
          <Timeline>
            <TimelineItem v-for="(item, index) in startNodeList" :key="index">
              <div style="display: flex;">
                <div>{{ item.nodeName }}</div>
                <div style="margin-left: 20px;">
                  <div v-for="(item2, index2) in item.approverUserList" style="cursor: pointer;">
                    <span>{{ item2.userName }}</span> <span>{{ item2.approvalTime }}</span>
                  </div>
                </div>


              </div>

            </TimelineItem>
          </Timeline>
        </div>
      </Modal>

      <Modal v-model:visible="visible" title="提示信息" @ok="handleOk">
        <p v-for="(item, index) in msgList">{{ item }}</p>
      </Modal>

      <Modal v-model:visible="visible2" title="数据处理中请等待" @ok="handleOk2" :ok-button-props="{ loading: !dataJson.id }">
        <div>第一次提交数据较多时请耐心等待</div>
        <div class="table-header-btn" v-for="item in waitList">
          <span style="padding-right: 5px;">{{ item.createTime }}</span>
          <span v-for="item in waitList" @click="openWaitFn(item)" :style="{ color: item.status ? 'green' : 'red' }">{{
            item.status ? "处理完成请提交审批" : "处理中" }}</span>
          <Spin v-if="item.status == 0"></Spin>
        </div>
      </Modal>
    </div>

  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref, h, toRaw, reactive, onMounted } from 'vue';

import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';
import {
  vxeTableColumns, confirmColumns, checkboxCountFn
} from './role.data';

import { formSchema, rules } from './role.data';
import { BasicModal, useModalInner } from '@/components/Modal';
import { useLocaleStore } from '@/store/modules/locale';

import { BasicTree, TreeItem } from '@/components/Tree';
import { approveCreateBefore, approveSubmit } from '@/api/heng/ywManage';

import { Modal, Timeline, TimelineItem, Spin } from 'ant-design-vue';

import { useMessage } from "@/hooks/web/useMessage";
import util from '@/utils/util';

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const { createMessage } = useMessage();

const visible = ref(false);
const msgList = ref([]);
const wait = ref(false);
const visible2 = ref(false);
var openNum = 0;
const localeStore = useLocaleStore();

const applyViewShow = ref(false);


const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: confirmColumns,
  filterConfig: {
    remote: true,
  },
  exportConfig: {},
  showFooter: true,

  footerData: [
    { orderNo: '合计' }
  ],
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },

  pagerConfig: {
    enabled: false
  },

});


const dataList = ref({});
const startNodeList = ref([]);
const dataJson = ref({ id: "" });//审批发起后 返回的数据
const loading = ref(false);
const totalObj = ref({});
const waitList = computed(() => { return localeStore.waitList });

const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  setModalProps({ confirmLoading: false });
  wait.value = data.wait;
  dataList.value = data.selectList;
  // console.log("---selectList::", data.selectList);
  tableRef.value?.reloadData(data.selectList);
  totalObj.value = checkboxCountFn(data.selectList);
  gridOptions.footerData = [{ orderNo: "合计:" + data.selectList.length + "条" }];
});



function applyViewOpen() {
  applyViewShow.value = true;
}

function applyViewClose() {
  applyViewShow.value = false;
}

const getTitle = computed(() => ('确认提交业务抽成审批？'));


//async function handleSubmit()

const handleSubmit = () => {
  try {
    let tableList = tableRef.value?.getFullData();
    if (tableList?.length == 0) {
      createMessage.error("暂无数据!");
      return;
    }
    // console.log(tableList);
    let dJson = { list: unref(tableList), type: 2 };
    loading.value = true;
    debugger;
    approveCreateBefore(dJson).then(res => {
      loading.value = false;
      openNum = 0;
      if (res && res.code == 200) {

        if (res.data.errorMsg) {
          msgList.value = res.data.errorMsg;
          visible.value = true;

        } else {
          openWaitList();
        }
      } else {
        createMessage.success(res.message);

      }
    })
  } catch (e) {
    console.log(e)
  } finally {
    setModalProps({ confirmLoading: false });

  }
}



function sunccFn(result) {
  if (result && result.code == 200) {
    applyViewClose();
    createMessage.success(result.message);
    closeModal()
    emit('success');
  } else {
    createMessage.error(result.message);
  }

}

function cancelFn() {
  openNum = 1;
  closeModal()
  emit('success');
}

function handleOk() {
  visible.value = false;
}
function openWaitList() {
  visible2.value = true;
}

onMounted(() => {
  setInterval(() => {
    trialLogListFn();

  }, 3000);
})

function trialLogListFn() {
  if (waitList.value.length && openNum == 0) {
    let index = 0;
    let b = false;
    for (let i = 0; i < waitList.value.length; i++) {
      let item = waitList.value[i];
      if (item.status == 1) {
        b = true;
        index = index;
      }
      // if (!visible2.value) {
      //   openWaitList();
      //   // openWaitFn(item);
      // }

    }
    if (b && !applyViewShow.value) {
      let item = waitList.value[index];
      openWaitFn(item);

    }
  }

}

//---------------

function openWaitFn(item) {

  dataJson.value = item;
  if (item.body) {
    let body = JSON.parse(item.body);
    startNodeList.value = body.startNodeList;
    applyViewOpen();
  }

}

function subFn() {
  loading.value = true;
  let data = { id: dataJson.value.id };
  approveSubmit(data).then(res => {
    loading.value = false;
    if (res && res.code == 200) {
      sunccFn(res);
    } else {
      createMessage.error(res.message);
    }
    // 
  })
}

function subClose() {
  applyViewShow.value = false;
  openNum = 1;
}

function handleOk2() {

  trialLogListFn();

}

</script>
<style lang="less">
.item-row {
  margin: 0 auto;

  //padding-left: 5%;
  .ant-form-item-label {
    flex: 0 0 28.5%;
    max-width: 28.5%;
  }
}

.lqfp-8 {
  //padding-left: 9% !important;

}
</style>
